package com.hljx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hljx.entity.SysAccountingUnit;
import com.hljx.excel.ExcelTransfer;
import com.hljx.vo.DictTypeVO;
import com.hljx.vo.SysDictVO;
import com.hljx.config.exception.DataException;
import com.hljx.dto.SysDictDTO;
import com.hljx.dto.SysDictPageDTO;
import com.hljx.entity.SysDict;
import com.hljx.entity.SysDictItem;
import com.hljx.mapper.sys.SysDictMapper;
import com.hljx.service.SysDictItemService;
import com.hljx.service.SysDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hljx.vo.TargetSysDictVO;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 字典 服务实现类
 * </p>
 *
 * @author gx
 * @since 2023-09-18
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    @Autowired
    SysDictItemService dictItemService;

    @Autowired
    SysDictMapper sysDictMapper;

    @Autowired
    private ExcelTransfer<SysDictVO> excelTransfer;

    @Autowired
    private ExcelTransfer<SysDict> dictExcelTransfer;

    @Override
    public List<DictTypeVO> selectDictDropdown(String dictName) {
        List<DictTypeVO> dictTypeVOList = new ArrayList<>();
        SysDict sysDict = this.getOne(new LambdaQueryWrapper<SysDict>().eq(SysDict::getName, dictName));
        if(sysDict != null){
            List<SysDictItem> list = dictItemService.list(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId, sysDict.getId()));
            if(!CollectionUtil.isEmpty(list)){
                list.forEach(s->{
                    DictTypeVO dictTypeVO = new DictTypeVO();
                    BeanUtil.copyProperties(s,dictTypeVO);
                    dictTypeVOList.add(dictTypeVO);
                });
            }
        }
        return dictTypeVOList;
    }

    @Override
    public Boolean saveOrUpdateDict(SysDictDTO dto) {
        long count = baseMapper.selectCount(new LambdaQueryWrapper<SysDict>().eq(SysDict::getCode, dto.getCode())
                .ne(dto.getId() != null, SysDict::getId, dto.getId()));
        if(count>0){
            throw new DataException("字典编码重复",201);
        }
        long result = baseMapper.selectCount(new LambdaQueryWrapper<SysDict>().eq(SysDict::getName,dto.getName()).ne(dto.getId() != null, SysDict::getId, dto.getId()));
        if(result>0){
            throw new DataException("字典名称重复",201);
        }
        SysDict sysDict = new SysDict();
        BeanUtil.copyProperties(dto,sysDict);
        return saveOrUpdate(sysDict);
    }

    @Override
    public Boolean deleteDict(Long id) {
        long count = dictItemService.count(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId, id));
        if(count>0){
            throw new DataException("请先删除该数据下的字典数据项",201);
        }
        return removeById(id);
    }

    @Override
    public Boolean updateDictStatus(Long id, Integer status) {
        update(new LambdaUpdateWrapper<SysDict>().eq(SysDict::getId,id).set(SysDict::getStatus,status));
        return dictItemService.update(new LambdaUpdateWrapper<SysDictItem>().eq(SysDictItem::getDictId,id).set(SysDictItem::getStatus,status));

    }

    @Override
    public IPage<SysDictVO> listSysDictByPage(SysDictPageDTO dto) {
        Page<SysDictVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        return baseMapper.listSysDictByPage(page, dto);
    }

    @Override
    public void export(SysDictPageDTO dto, HttpServletResponse response) throws ClassNotFoundException {
        List<SysDictVO> list = new ArrayList<>();
        if (dto.getType() == null) {
            throw new DataException("入参数据为空",201);
        }
        if (dto.getType() == 1) {
            Page<SysDictVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
            IPage<SysDictVO> iPage = baseMapper.listSysDictByPage(page, dto);
            list = iPage.getRecords();
        }
        excelTransfer.exportExcel(response, list, "字典管理", "sheet1", SysDictVO.class);
    }

    @Override
    public void importExcel(MultipartFile file, HttpServletResponse response) throws ClassNotFoundException, IOException {
        List<SysDict> list = list(Wrappers.lambdaQuery(SysDict.class));
        dictExcelTransfer.importExcel(file, this, lists -> {
            ArrayList<SysDict> arrayList = new ArrayList<>();
            lists.forEach(e -> {
                if (list.stream().noneMatch(l -> e.getName().equals(l.getName())) || list.stream().noneMatch(l -> e.getCode().equals(l.getCode())) ) {
                    e.setStatus("是".equals(e.getEnable()) ? 1 : 0);
                    arrayList.add(e);
                }
            });
            return arrayList;
        });
    }

    /**
     * @param
     * @author hxc
     * @date 2023/9/26 13:54
     * @version 1.0
     * @see "指标管理下拉框"
     */
    @Override
    public List<TargetSysDictVO> sysDictPull() {
        List<TargetSysDictVO> targetSysDictVOS = sysDictMapper.sysDictPull();
        return targetSysDictVOS;
    }

    @Override
    public List<SysDictVO> listProjectTargetAdministrationPull(String code) {
        List<SysDictVO> sysDictVOS = sysDictMapper.listProjectTargetAdministrationPull(code);
        return sysDictVOS;
    }
}
